<?php

   // auto_backup_setup.php V2.1

   require('includes/application_top.php');
   $werror = (isset($_GET['status']) ? $_GET['status'] == 1 : '');
   // make directory
   $action = (isset($_GET['confirm']) ? $_GET['confirm'] : '');
   if ($action == 'yes' && !is_dir(DIR_FS_BACKUP))
   {
      mkdir(DIR_FS_BACKUP);
      tep_redirect(tep_href_link('auto_backup_setup.php'));
   }

   function newfname($path, $filename, $ext)
   {
      if (is_file( $path . $filename ) )
      {
         $filename = str_replace($ext, '', $filename);
         $i = 1;
         while ( is_file( $path . ($nfilename = $filename . '(' . $i++ . ')' . $ext ) ) );
         $filename = $nfilename;
      }
      return $filename;
   }

   // add call to app top
   $action = (isset($_GET['addline']) ? $_GET['addline'] : '');
   if ($action == 'create')
   {
      $file = DIR_WS_INCLUDES . 'application_top.php';
      $nfile = DIR_WS_INCLUDES . newfname(DIR_WS_INCLUDES, 'application_top.php.backup', '.php.backup');
      $apt = file_get_contents($file);
      $len = strripos($apt,'?>');
      copy($file, $nfile);
      $addition = "\n" . '//call auto backup (added by auto_backup_setup)' . "\n" . '  if (tep_session_is_registered(\'admin\') && ENABLE_AUTO_BACKUP != \'false\') require(DIR_WS_INCLUDES .\'auto_backup_db.php\');' . "\n" . '?>' . "\n";
      if (($apt = fopen($file, "r+")) && $len)
      {
         fseek($apt, $len);
         if (fwrite($apt,$addition) == false) $werror = true;
         if (fclose($apt) === false) $werror = true;
      }
      else
      {
         $werror = true;
      }
      tep_redirect(tep_href_link('auto_backup_setup.php','status='.($werror ? 1 : 0)));
   }
	preg_match('/[\d\.]+/', PHP_VERSION, $matches);
   $version = intval($matches[0]); 
   if ( $version >= 5) //check server ok
   {
      // check configuration done already
      $chk_query = tep_db_query("select * from configuration_group where configuration_group_title = 'Auto Backup'");

      if ($check = tep_db_num_rows($chk_query))
      {
         $chk_query2 = tep_db_query("select * from configuration where configuration_key = 'BACKUP_SPLIT'"); // exists, upgrade due?
         if (!tep_db_num_rows($chk_query2))
         {
            $result = tep_db_fetch_array($chk_query);
            $cfg_group_id = $result['configuration_group_id'];
            $error =  (tep_db_query("DELETE FROM `configuration` WHERE `configuration_group_id` = " . $cfg_group_id) == false);
            $upgrade = true;
         }
         else 
         {    
				if (!tep_db_num_rows(tep_db_query("select * from configuration where configuration_key = 'BACKUP_MAIL_CRON'")))  // V4.1  upgrade?  
         	{      
            	$result = tep_db_fetch_array($chk_query);
            	$cfg_group_id = $result['configuration_group_id'];
            	$error =  (tep_db_query("INSERT INTO `configuration` (`configuration_title`, `configuration_key`, `configuration_value`, `configuration_description`, `configuration_group_id`, `sort_order`, `last_modified`, `date_added`, `use_function`, `set_function`) VALUES ('Email Cron Backups', 'BACKUP_MAIL_CRON', 'false', 'Email cron backups on completion.<br /><br />By default backups are emailed to the store owner (My Store configuration)', '" . $cfg_group_id . "', 49, NULL, now(), '', 'tep_cfg_select_option(array(\'true\', \'false\'),'),('Enable Auto Backup', 'ENABLE_AUTO_BACKUP', 'true', 'Set to true to enable Auto Backup.', '" . $cfg_group_id . "', 0, NULL, now(), '', 'tep_cfg_select_option(array(\'true\', \'false\'),')") == false);
            	$upgrade = '4 to 4.2';
            	$cfg_group_id = false;
         	}
         	elseif (!tep_db_num_rows(tep_db_query("select * from configuration where configuration_key = 'ENABLE_AUTO_BACKUP'"))) // V4.2 upgrade? 
         	{
            	$result = tep_db_fetch_array($chk_query);
            	$cfg_group_id = $result['configuration_group_id'];
            	$error =  (tep_db_query("INSERT INTO `configuration` (`configuration_title`, `configuration_key`, `configuration_value`, `configuration_description`, `configuration_group_id`, `sort_order`, `last_modified`, `date_added`, `use_function`, `set_function`) VALUES ('Enable Auto Backup', 'ENABLE_AUTO_BACKUP', 'true', 'Set to true to enable Auto Backup.', '" . $cfg_group_id . "', 0, NULL, now(), '', 'tep_cfg_select_option(array(\'true\', \'false\'),')") == false);
            	$upgrade = '4.1 to 4.2';
            	$cfg_group_id = false;	
         	}	
         }	
      }
      else // new install
      {
         $cfg_group_query = "INSERT INTO configuration_group (configuration_group_title, configuration_group_description, sort_order) VALUES ('Auto Backup', 'Auto Backup configuration options', '12')";
         if (tep_db_query($cfg_group_query) == false)  $error = true;
         $cfg_group_id = tep_db_insert_id();
      }
      if($cfg_group_id) // insert configuration values
      {
         $cfg_sql_array = array(array("INSERT INTO `configuration` (`configuration_title`, `configuration_key`, `configuration_value`, `configuration_description`, `configuration_group_id`, `sort_order`, `last_modified`, `date_added`, `use_function`, `set_function`) VALUES ('Auto Backup Interval', 'BACKUP_INTERVAL', '20', 'Alter the automatic dBase backup interval in minutes, i.e. 20mins (5 mins minimum).<br /><br />When a new backup is created the previous interim one is deleted, subject to the <b>Backup Archive Interval</b>', '" . $cfg_group_id . "', 30, NULL, now(), NULL, NULL)"),
         array("INSERT INTO `configuration` (`configuration_title`, `configuration_key`, `configuration_value`, `configuration_description`, `configuration_group_id`, `sort_order`, `last_modified`, `date_added`, `use_function`, `set_function`) VALUES ('Enable Auto Backup', 'ENABLE_AUTO_BACKUP', 'true', 'Set to true to enable Auto Backup.', '" . $cfg_group_id . "', 0, NULL, now(), '', 'tep_cfg_select_option(array(\'true\', \'false\'),')"),
         array("INSERT INTO `configuration` (`configuration_title`, `configuration_key`, `configuration_value`, `configuration_description`, `configuration_group_id`, `sort_order`, `last_modified`, `date_added`, `use_function`, `set_function`) VALUES ('Backup Archive Interval', 'BACKUP_SAVE_INTERVAL', '24', 'Set Interval to keep backups in hours. Suggest 24 Hrs so a backup archive is kept once a day.<br /><br />That means when a new backup is created, the previous interim one is deleted so long as another older but less than this age exists.', '" . $cfg_group_id . "', 31, NULL, now(), NULL, NULL)"),
         array("INSERT INTO `configuration` (`configuration_title`, `configuration_key`, `configuration_value`, `configuration_description`, `configuration_group_id`, `sort_order`, `last_modified`, `date_added`, `use_function`, `set_function`) VALUES('GZip Backups', 'BACKUP_ZIP', 'gzip', 'Enable GZipping of auto-backup files.<br /><br />Once a backup has been successfully gzipped the uncompressed original is automatically deleted.', '" . $cfg_group_id . "', 42, NULL, now(), '', 'tep_cfg_select_option(array(''gzip'', ''false''),')"),
         array("INSERT INTO `configuration` (`configuration_title`, `configuration_key`, `configuration_value`, `configuration_description`, `configuration_group_id`, `sort_order`, `last_modified`, `date_added`, `use_function`, `set_function`)
         VALUES ('Split Backups On Timeout', 'BACKUP_SPLIT', 'extend', 'Split backups if approaching max execution time or extend execution time.<br /><br />Splitting reduces problems with admin page loads/updates if backup takes too long but may result in invalid backups if database changes during split.', '" . $cfg_group_id . "', 44, NULL, now(), '', 'tep_cfg_select_option(array(\'split\', \'extend\'),');"),
         array("INSERT INTO `configuration` (`configuration_title`, `configuration_key`, `configuration_value`, `configuration_description`, `configuration_group_id`, `sort_order`, `last_modified`, `date_added`, `use_function`, `set_function`)
         VALUES ('Auto Backup Displayed Time Format', 'BACKUP_DATETIME_FMT', 'true', 'True = Use the auto backup date/time format<br />(23rd Feb 2012 15:42) or<br /><br />\r\nFalse = use your system date/time format,<br />ie 23/02/2012 15:34:33', '" . $cfg_group_id . "', 46, NULL, now(), '', 'tep_cfg_select_option(array(\'true\', \'false\'),');"),
         array("INSERT INTO `configuration` (`configuration_title`, `configuration_key`, `configuration_value`, `configuration_description`, `configuration_group_id`, `sort_order`, `last_modified`, `date_added`, `use_function`, `set_function`)
         VALUES ('Auto Run Auto Backup Delete', 'AUTO_BACKUP_DELETE', 'false', 'Auto Backup Delete is meant to be called as a cron job, however you can enable auto-backup to call it, which it will do whenever the log file is over a day old or does not exist.', '" . $cfg_group_id . "', 48, NULL, now(), '', 'tep_cfg_select_option(array(\'true\', \'false\'),');"),
         array("INSERT INTO `configuration` (`configuration_title`, `configuration_key`, `configuration_value`, `configuration_description`, `configuration_group_id`, `sort_order`, `last_modified`, `date_added`, `use_function`, `set_function`)
         VALUES ('Backup Delete Interval', 'BACKUP_DELETE', '30', 'The number of days to keep backups before they are permanently removed', '" . $cfg_group_id . "', 50, NULL, now(), '', '')"),
         array("INSERT INTO `configuration` (`configuration_title`, `configuration_key`, `configuration_value`, `configuration_description`, `configuration_group_id`, `sort_order`, `last_modified`, `date_added`, `use_function`, `set_function`) VALUES ('Email Cron Backups', 'BACKUP_MAIL_CRON', 'false', 'Email cron backups on completion.<br /><br />By default backups are emailed to the store owner (My Store configuration)', '" . $cfg_group_id . "', 49, NULL, now(), '', 'tep_cfg_select_option(array(\'true\', \'false\'),');")	);

         foreach ($cfg_sql_array as $sql_array) foreach ($sql_array as $value) if (tep_db_query($value) == false)  $error = true;

      }
      else
      {
         if (!$upgrade) $error = 2;
      }

   }

   require(DIR_WS_INCLUDES . 'template_top.php');
?>

<!-- body //-->
 <table border="0" width="100%" cellspacing="2" cellpadding="2">
  <tr>
   <td width="100%" valign="top"> <table border="0" width="100%" cellspacing="0" cellpadding="0">
      <tr>
        <td class="pageHeading"><?php echo 'Auto Backup Setup'; ?></td>
          </tr>
          <tr>
        <td><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
      </tr>
<?php
   if ($version > 4)
   {
   	$apt = file_get_contents  (DIR_WS_INCLUDES . 'application_top.php');
         if (!strripos($apt, 'auto_backup_db.php') && ( function_exists('at_message') || function_exists('at_microtime_float') || function_exists('at_comp') || function_exists('at_gzip') || function_exists('at_date')))
         {
?>   
       <tr>
        <td class="main"><div style="border: 1px solid; width:600px; padding:20px; text-align: center;">
				Warning, it appears you have not yet installed Auto Backup,<br />but some of the functions created by Auto Backup already exist on your system!<br /><br />
				Conflicting functions found: 
<?php
      		$functions = array('at_message','at_microtime_float','at_comp','at_gzip','at_date');
      		foreach ($functions as $test) if (function_exists($test)) $list .= $test . ', ';
      		echo rtrim($list, ', ');

?>
				<br /><br />Please resolve these conflicts before completing this installation. 
				<br /><br />However if you have in-fact already completed a Auto Backup installation, ignore this warning.<br />        
         </div></td>
      </tr>
      <tr>
        <td><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
      </tr>
<?php         
         }	
?>
      <tr>
        <td class="main"><div style="border: 1px solid; width:600px; padding:10px 20px 20px; text-align: left;">
				Configuration Setup:<br /><br /><div style="text-align:center; width:100%;">
<?php
      if ($error)
      echo ($error == 2 ? ($action == 'yes' ? 'Setup Complete.' : 'Auto Backup configuration appears to be set up OK. Made no changes.') : 'Sorry, there was a problem encountered during setup!');
      else
      echo $upgrade ? 'Auto Backup configuration has been updated successfully' . ($upgrade === true ? '.' : ' from ' . $upgrade . '.') : 'Auto Backup has been configured successfully.';

?>
        </div> </div></td>
      </tr>
      <tr>
        <td><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
      </tr>
			<tr>
        <td class="main"> <div style="border: 1px solid; width:600px; padding:20px; text-align: center;">
<?php
      $ff = true;
      if (is_dir(DIR_FS_BACKUP))
      {
         echo 'Backup directory found, ';
         if (is_writeable(DIR_FS_BACKUP))
         {
            echo 'and is writeable. OK.';
         }
         else
         {
            echo ' but is not writeable, please set permissions.';
            $ff = false;
         }
      }
      else
      {
         echo 'Backup directory not found!<br /><br />Please confirm you wish to create a backup directory at: ' . DIR_FS_BACKUP .'<br /><br />';
         echo tep_draw_form('mkdir', 'auto_backup_setup.php', '', 'get') . tep_draw_hidden_field('confirm', 'yes') . '<input type="submit" value="Yes, create the directory" class="button"></form>';
         $ff = false;
      }
?>
        </div></td>
      </tr>
			 <tr>
        <td><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
      </tr>
			<tr>
        <td class="main"><div style="border: 1px solid; width:600px; padding:10px 20px 20px; text-align: left;">
				File Checks:<br /><div style="text-align:center; width:100%;">
<?php
      if (file_exists(DIR_WS_INCLUDES . 'auto_backup_db.php'))
      {
         echo 'Auto Backup file found in place, OK';
      }
      else
      {
         $ff = false;
         echo 'ERROR, Auto Backup file not found in:<br /><b>' . DIR_WS_ADMIN . DIR_WS_INCLUDES . '</b> folder, please add it.';
      }
      echo '<br /><br />';
      if (file_exists(DIR_WS_INCLUDES . 'auto_backup_delete.php'))
      {
         echo 'Auto Backup Delete file found in place, OK';
      }
      else
      {
         $ff = false;
         echo 'ERROR, Auto Backup Delete file not found in:<br /><b>' . DIR_WS_ADMIN . DIR_WS_INCLUDES . '</b> folder, please add it.';
      }
      echo '<br /><br />';
      if (file_exists(DIR_WS_INCLUDES . 'mail_backups.php'))
      {
         echo 'Mail Backups file found in place, OK';
      }
      else
      {
         $ff = false;
         echo 'ERROR, Mail Backups file not found in:<br /><b>' . DIR_WS_ADMIN . DIR_WS_INCLUDES . '</b> folder, please add it.';
      }
      echo '<br /><br />';
      if (file_exists(DIR_WS_INCLUDES . 'mail_cron_backups.php'))
      {
         echo 'Mail Cron Backups file found in place, OK';
      }
      else
      {
         $ff = false;
         echo 'ERROR, Mail Cron Backups file not found in:<br /><b>' . DIR_WS_ADMIN . DIR_WS_INCLUDES . '</b> folder, please add it.';
      }
      echo '<br /><br />';
      if (file_exists(DIR_WS_LANGUAGES . $language . '/auto_backup.php'))
      {
         echo 'Auto Backup Language file found in place, OK';
      }
      else
      {
         $ff = false;
         echo 'ERROR, Auto Backup Language file not found in:<br /><b>' . DIR_WS_ADMIN . DIR_WS_LANGUAGES . $language . '/</b> folder, please add it.';
      }
 ?>
			</div></div></td>
			</tr>
<?php
      if ($ff) // past basic checks, offer to edit app top if needed
      {
?>
      <tr>
        <td><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
      </tr>
			<tr>
        <td class="main"> <div style="border: 1px solid; width:600px; padding:10px 20px 20px; text-align: left;">
				Edits:<br /><div style="text-align:center; width:100%;">
<?php
         $apt = file_get_contents  (DIR_WS_INCLUDES . 'application_top.php');
         if (!strripos($apt, 'require(DIR_WS_INCLUDES .\'auto_backup_db.php\'') )
         {
            $ff = false;
            echo 'Oops, application_top.php does not appear to contain a line to call Auto Backup,<br />do you wish me to add it? (Advise BACKUP application_top.php first) <br /><br />';
            echo tep_draw_form('mkfile', 'auto_backup_setup.php', '', 'get') . tep_draw_hidden_field('addline', 'create') . '<input type="submit" value="Yes, Change It For Me" class="button"></form>';
         }
         else
         {
            echo 'Great, application_top.php appears to contain a line to call Auto Backup.';
         }

         if ($werror) echo '<br /><br />An attempt to a modify application_top.php has been undertaken, but failed,<br />please edit the file manualy.'

 ?>
			</div></div></td>
      </tr>
<?php
      }
?>
			<tr>
        <td><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
      </tr>
			<tr>
        <td class="main"> <div style="border: 1px solid; width:600px; padding:20px; text-align: center;">
<?php
      if ((!$error || $error == 2) && !$werror && $ff) echo 'Installation successful, setup has past all checks OK!';
      else echo 'Setup has failed some checks, please check your install or apply fixes suggested above.<br /><br />' . tep_draw_form('check', 'auto_backup_setup.php', '', 'get') . '<input type="submit" value="Retest Installation" class="button"></form>';
      if ((!$error || $error == 2) && !$werror && $ff) echo '<br /><br />' . tep_draw_form('check', 'auto_backup_setup.php', '', 'get') . tep_draw_hidden_field('test', 'at_backup') . '<input type="submit" value="Test Run Auto Backup" class="button"></form>';
 ?>
			</div></td>
			</tr>
<?php
   }
   else
   {
?>
			<tr>
        <td class="main">
        <div style="border: 1px solid; width:600px; padding:20px; text-align: center;">
        Error: Auto Backup V4 requires at least PHP Version 5, your server reports version <?php echo $matches[0]; ?>
        <br /><br />The previous Version of Auto Backup does support PHP Version 4.

			</div></td>
			</tr>
<?php
   }
?>
    </table> </td>
<!-- body_text_eof //-->
  </tr>
</table>
<!-- body_eof //-->

<!-- footer //-->
<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
<!-- footer_eof //-->
<br />
</body>
</html>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>
